package controllers

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"net/http"
	"reflect"
	"smart_home/api/models"
	"smart_home/api/utils/token"
	"tools"
)

type BaseController struct {
	beego.Controller
	User           *models.User
	Token          string // token
	RegistrationId string // 极光id
	DeviceId       string // 设备id
}

func (c *BaseController) Prepare() {
	if tk := c.Ctx.Input.Header("token"); len(tk) > 0 {
		c.Token = tk
		if t := token.Get(tk); t != nil {
			c.RegistrationId = t.RegId
			c.DeviceId = t.DevId
			c.User, _ = models.GetUserById(t.Uid)
		}
	}

	// 服务器认证
	if st := c.Ctx.Input.Header("st"); len(st) > 0 {
		suid := c.Ctx.Input.Header("suid")
		c.User, _ = models.GetUserById(suid)
	}

	if c.User != nil {
		logs.Debug("current user:%+v, token:%s\n", c.User, c.Token)
	}
}

func (c *BaseController) Finish() {
	// 防止重复提交【操作完成去除标志】
	key := tools.MD5Encode(fmt.Sprintf("%s-%s", c.Ctx.Input.URL(), c.Token))
	defer tools.UnRLock(key)
}

func (c *BaseController) Error(err error) {
	c.Data["json"] = &models.ResultMsg{
		Code:   0,
		Msg:    err.Error(),
		Result: nil,
	}
	c.ServeJSON()
}

func (c *BaseController) Success(data interface{}) {
	c.Data["json"] = &models.ResultMsg{
		Code:   1,
		Msg:    "success",
		Result: data,
	}
	c.ServeJSON()
}

// @Title ParseData
// @Description 解析数据到结构
func (c *BaseController) ParseData(data interface{}) error {
	if reflect.TypeOf(data).Elem().Kind() != reflect.Struct {
		return errors.New("data isn't struct")
	}
	if c.Ctx.Request.Method == http.MethodPut {
		bytes, err := ioutil.ReadAll(c.Ctx.Request.Body)
		if err != nil {
			return err
		}
		err = json.Unmarshal(bytes, data)
		if err != nil {
			return err
		}
		return nil
	} else {
		err := c.ParseForm(data)
		return err
	}
}
